<?php

namespace AuthEntity\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use AuthEntity\Form\RegistrationForm;
use AuthEntity\Model\UsersEntity;

use Zend\Mail\Message;

class RegistrationController extends AbstractActionController {

    protected $usersMapper = null;

    public function indexAction() {
        $usersEntity = new UsersEntity();
        $form = new RegistrationForm('registration');
        $form->bind($usersEntity);

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $user = $this->getUsersMapper()->saveUser($usersEntity);                
                $this->sendConfigmationEmail($usersEntity);
                
                if ($user->getGeneratedValue()) {
                    $this->flashMessenger()->addMessage('Registration Successful');
                }
                $this->redirect()->toRoute('authentity', array('controller' => 'Registration', 'action' => 'registration-sucess'));
            }
        }
        
        return new ViewModel(array(
            'form' => $form
        ));
    }
    
    public function sendConfigmationEmail(UsersEntity $user)
    {
        $transport = $this->getServiceLocator()->get('mail.transport');
        $message = new Message();
        $this->getRequest()->getServer();
        $message->addTo($user->getUsrEmail())
				->addFrom('supermouseno1@gmail.com')
				->setSubject('Please, confirm your registration!')
				->setBody("Please, click the link to confirm your registration => " . 
					$this->getRequest()->getServer('HTTP_ORIGIN') .
					$this->url()->fromRoute('auth/default', array(
						'controller' => 'registration', 
						'action' => 'confirm-email', 
						'id' => $user->getUsrRegistrationToken())));
		$transport->send($message);
    }
    
    public function getUsersMapper() {
        $sm = $this->getServiceLocator();
        $this->usersMapper = $sm->get('UsersEntityMapper');
        return $this->usersMapper;
    }
}
